import '../public/index'
import url from '../data/url'
import request from '../data/request'
import { header } from '../data/config'
import { catchError } from '../data/util'

import {
  cusId      as valid_cusId,
  identifier   as valid_identify,
} from '../data/validate'

const base             = url.base,
      addTerminal      = request.addOrModifyTerminal,
      getDeveloperList = request.getDeveloperList,
      getBuildingList  = request.getBuildingList,
      getKeyboardList  = request.getKeyboardList,
      // 收款方列表
      getReceivingList = request.getReceiving,
      // 合同列表
      getPactList      = request.getPact;

// 页面标题
const title  = '终端管理',
      action = '添加'

let form = new Vue({
  el: '#form',
  data: () => {
    return ({
      cusId                 : '',
      identifier            : '',
      developerList         : [],
      developersId          : '',
      dropertyList          : [],
      propertyId            : '',
      type                  : '1',
      keyBoardId            : '',
      keyBoardList          : [],
      // 收款方id
      receivablesPeopleId   : '',
      // 收款方列表
      receivablesPeopleList : [],
      // 合同id
      contractId            : [],
      // 合同列表
      contractList          : [],
      publicKey             : '',
      privateKey            : '',
      control               : '',
      isLock                : true
    })
  },
  mounted: function() {

    let that = this

    let loading = layer.msg('初始化数据中...', {
      icon: 16,
      time: 0
    })

    Promise
      .all([this.getDeveloper(), this.getBuilding(), this.getKeyboard(), this.getReceivingList(), this.getPactList()])
      .then((res) => {

        layer.close(loading)

        that.developerList         = res[0];
        that.dropertyList          = res[1];
        that.keyBoardList          = res[2];
        that.receivablesPeopleList = res[3];
        that.contractList          = res[4];

        that.isLock                = false;

        valid()

        setTimeout(() => {

          that.initSelect();
        }, 0)
      })
      .catch((error) => {

        layer.close(loading)
        layer.msg(error || '初始化数据失败', {
          icon: 5
        })
      })

  },
  methods: {
    // 获取开发商列表
    getDeveloper: () => (
      new Promise((resolve, reject) => {

            $.ajax({
              url: base + getDeveloperList,
              dataType: 'json',
              headers: header
            })
            .done(function(res) {
              if (res.code === 0) {
                resolve(res.object)
              }
              reject(res.message)
            })
            .fail(function() {
              console.log("error")
              reject()
            })
            .always(function() {
              catchError(arguments)
            })

          })

    ),
    // 获取楼盘列表
    getBuilding: () => (
      new Promise((resolve, reject) => {

            $.ajax({
              url: base + getBuildingList,
              headers: header
            })
            .done(function(res) {
              if (res.code === 0) {
                resolve(res.object)
              }
              reject(res.message)
            })
            .fail(function() {
              console.log("error")
              reject()
            })
            .always(function(res) {
              catchError(arguments)
            })

          })

    ),
    // 获取金属键盘列表
    getKeyboard: () => (
      new Promise((resolve, reject) => {

            $.ajax({
              url: base + getKeyboardList,
              headers: header
            })
            .done(function(res) {
              if (res.code === 0) {
                resolve(res.object)
              }
              reject(res.message)
            })
            .fail(function() {
              console.log("error")
              reject()
            })
            .always(function(res) {
              catchError(arguments)
            })

          })

    ),
    // 获取收款方列表
    getReceivingList: () => (
      new Promise((resolve, reject) => {

            $.ajax({
              url: base + getReceivingList,
              headers: header
            })
            .done(function(res) {
              if (res.code === 0) {
                resolve(res.object)
              }
              reject(res.message)
            })
            .fail(function() {
              console.log("error")
              reject()
            })
            .always(function(res) {
              catchError(arguments)
            })

          })

    ),
    // 获取合同列表
    getPactList: () => (
      new Promise((resolve, reject) => {

            $.ajax({
              url: base + getPactList,
              headers: header
            })
            .done(function(res) {
              if (res.code === 0) {
                resolve(res.object)
              }
              reject(res.message)
            })
            .fail(function() {
              console.log("error")
              reject()
            })
            .always(function(res) {
              catchError(arguments)
            })

          })

    ),
    checkType: function (e) {
      let $el = $(e.target),
          val = $el.val();

      this.type = val;
      this.control.clear();

      // 清空Dom重新渲染后的数据
      this.keyBoardId = '';
      this.receivablesPeopleId = [];
      this.contractId = [];
      this.publicKey = '';
      this.privateKey = '';
    },
    initSelect: function () {
      let that = this;

      $(this.$refs.developersId)
        .selectize({
          create: true,
          onChange: function (val) {
            that.developersId = val;
          }
        })

      let $area = $(this.$refs.keyBoardId)
        .selectize({
          create: true,
          onChange: function (val) {
            that.keyBoardId = val;
          }
        });

      this.control = $area[0].selectize;
    }
  }
})

function valid() {

  let form_valid,
      $form = $('#form')

  $.validator.setDefaults({ // 只能放在validate规则配置之前

    // 提交事件
    submitHandler: () => {
      console.log('submit!')

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      form.isLock = true

      $.ajax({
        url: base + addTerminal,
        type: 'POST',
        contentType: 'application/json',
        headers: header,
        data: JSON.stringify({
          cusId               : form.cusId ==='' ? form.identifier : form.cusId,
          identifier          : form.identifier,
          type                : form.type,
          developersId        : form.developersId,
          propertyId          : form.propertyId,
          keyBoardId          : form.keyBoardId,
          receivablesPeopleId : form.receivablesPeopleId,
          contractId          : form.contractId.join(','),
          publicKey           : form.publicKey,
          privateKey          : form.privateKey
        })
      })
        .done(function(res) {
          console.log(res)

          if (res.code === -1 ) {
            layer.msg(res.message, {
              icon: 5
            })

            return
          }

          layer.msg(`${action}${ title }成功`, {
            icon: 6
          })

          // 重置表单
          $.extend(form.$data, form.$options.data())

          setTimeout(() => {
            window.location = './index.html'
          }, 1000)
        })
        .fail(function(res) {
          console.log(res)

          layer.msg(`${action}${ title }失败`, {
            icon: 5
          })

          console.log("error");
        })
        .always(function(res) {

          layer.close(loading_modal)
          form.isLock = false

        })

    }
  });

  // 验证
  form_valid = $form.validate({
    errorPlacement:function(error, element) {
      error.appendTo(element.parents('.col-xs-24'))
    },
    rules: {
      cusId: valid_cusId,
      identifier: valid_identify,
      type: {
        required: true
      },
      developersId: {
        required: true
      },
      propertyId: {
        required: true
      },
/*      publicKey: {
        required: true
      },
      privateKey: {
        required: true
      }*/
    }
  })

}